#coding:utf-8

import os
import wx
from speek import speek
from catch import catch
import threading,time

class text(wx.Frame):
    start = 0
    end = 0
    currentLine = 0
    c = None
    news_list = []
    show_poi_flag = False
    def __init__(self):
        #sys.setdefaultencoding('cp936')
        wx.Frame.__init__(self, None, -1, '语音朗读'.decode("utf-8" , "ignore"), size=wx.Size(500, 350))

    #create the button
        
        #self.seg = SEG()
        #print self.tts.GetVoiceNames()
        #[u'MSMike', u'MSMary', u'MSSam', u'SampleTTSVoice', u'MSSimplifiedChineseVoice']
        

        id = wx.NewId()
        panel = wx.Panel(self)
        #show = wx.StaticText(panel, -1, "准备开始...".decode("utf-8" , "ignore"))
        #show.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
        #show.SetSize(show.GetBestSize())
        #self.show = show
        
        #wx.EVT_BUTTON(self, id, self.read("d:/设计模式_20091017.txt"))

#        startId = wx.NewId()
#        btnOpen = wx.Button(panel, startId, u'打开文件')
#        #wx.EVT_BUTTON(self, id, self.read)
#        self.Bind(wx.EVT_BUTTON, self.onOpen, btnOpen)
        
        startId = wx.NewId()
        btnStart = wx.Button(panel, startId, u'开始朗读')
        #wx.EVT_BUTTON(self, id, self.read)
        self.Bind(wx.EVT_BUTTON, self.onRead, btnStart)
        
        convertId = wx.NewId()
        btnConvert = wx.Button(panel, convertId, u'开始转换')
        #wx.EVT_BUTTON(self, id, self.read)
        self.Bind(wx.EVT_BUTTON, self.onToWav, btnConvert)

        pauseId = wx.NewId()
        btnPause = wx.Button(panel, pauseId, u'暂停')
        self.Bind(wx.EVT_BUTTON, self.onPause, btnPause)

        resumeId = wx.NewId()
        btnResume = wx.Button(panel, resumeId, u'继续')
        self.Bind(wx.EVT_BUTTON, self.onResume, btnResume)
        
        nextId = wx.NewId()
        btnNext = wx.Button(panel, nextId, u'下一个')
        self.Bind(wx.EVT_BUTTON, self.onStop, btnNext)

        #stopId = wx.NewId()
        #btnStop = wx.Button(panel, stopId, u'停止')
        #self.Bind(wx.EVT_BUTTON, self.stop, btnStop)
        
        #菜单
        menuSizer  = wx.BoxSizer(wx.HORIZONTAL)
        #menuSizer.Add(btnOpen, 0, wx.ALL, 10)
        menuSizer.Add(btnStart, 0, wx.ALL, 10)
        menuSizer.Add(btnConvert, 0, wx.ALL, 10)
        menuSizer.Add(btnNext, 0, wx.ALL, 10)
        menuSizer.Add(btnPause, 0, wx.ALL, 10)
        menuSizer.Add(btnResume, 0, wx.ALL, 10)
        #menuSizer.Add(btnStop, 0, wx.ALL, 10)
        
        #list
        workArea  = wx.BoxSizer(wx.HORIZONTAL)
        #workArea.SetMinSize(wx.Size(200 , 500))
        self.fileList = wx.ListBox(panel, -1, (800, 800), wx.Size(150 , 200))
        self.textArea = wx.TextCtrl(panel, -1, "",
                        size=(310, 200), style=wx.TE_MULTILINE|wx.TE_RICH2)
        #self.fileList.SetSizeWH(500 , 200)
        #help(self.fileList)
        workArea.Add(self.fileList , 0 , wx.ALL)
        workArea.Add(self.textArea , 0 , wx.ALL|wx.EXPAND)
        #self.Bind(wx.EVT_BUTTON, sele, source, id, id2)
        #添加
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(menuSizer, 0, wx.ALL|wx.EXPAND, 10)
        sizer.Add(workArea, 0, wx.ALL|wx.EXPAND, 10)
        #sizer.Add(show, 0, wx.ALL, 10)
        
        panel.SetSizer(sizer)
        panel.Layout()

        self.speek = speek(self.info , self)
        
        self.SetStatusBar(wx.StatusBar(self))
        self.info("准备".decode("utf-8" , "ignore"))
        self.readThread = None
        self.toWavThread = None
        self.readDir = None
        
        self.panel = panel
        
        panel.Bind(wx.EVT_SIZE, self.OnCPSize)
        self.c = catch(self)
        threading._start_new_thread(self.auto_read , (self, None))
        #self.fileList.Append("1111111111")
    def OnCPSize(self , evt):
            self.panel.SetPosition((0,0))
            self.panel.SetSize(evt.GetSize())
            print 0
            
    def onOpen(self , h=None):
        dlg = wx.FileDialog(
            self, message="选择文件",
            defaultDir="d:/22", 
            defaultFile="选择文件",
            style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
           
            #for file in  dlg.GetPaths():
            names = []
            for f in dlg.GetPaths():
                names.append(os.path.basename(f))
            self.fileList.SetItems(names)
            #记录目录
            self.readDir = os.path.dirname(dlg.GetPath())
               
    def onRead(self , fileName):
        #fileName = "d:/设计模式_20091017.txt"
        #text = self.loadFile(fileName)
        
        
        if self.speek.isSpeeking():
            self.speek.stop()
        if self.readThread != None and self.readThread.isAlive():
            self.readThread.join(2)
            
        if self.fileList.IsEmpty():
            wx.Dialog(self, -1, '没有文件'.decode("utf-8" , "ignore"))
        
        self.readThread = threading.Thread(None,self.read())  
        self.readThread.start() 
        #self.speek.read(fileName)
        #self.tts.Speak(text , pyTTS.tts_is_xml, pyTTS.tts_async)
    def auto_read(self , top , t):
        while True:
            if len(top.news_list) > 0 :
                
                url , title , content = top.news_list[0]
                result = title + "\n" +content
                top.textArea.SetValue(result)
                top.fileList.SetSelection(0)
                top.read(result)
                top.news_list.pop(0)
                top.fileList.Delete(0)
                
            else:
                time.sleep(1)
    def onStop(self , h=None):
        print u"停止"
        self.speek.stopRead()
    def read(self , content):

        self.speek.readText(content)
#        if wait:
#            while True:
#                print self.end , len(content)
#                if self.end == len(content):
#                    break
#                else:
#                    time.sleep(1)
        

        
    def onToWav(self , path):
        if self.toWavThread != None and self.toWavThread.isAlive():
            self.toWavThread.join(2)
            
        #help(threading)
        #self.toWavThread = threading.Thread(None , )
        
        #self.toWavThread.start()
        self.toWav()
        
    #转换成wav
    def toWav(self):
        #path = "d:/22"
        if len(self.fileList.GetChecked()) == 0:
            wx.MessageBox('还没有选择文件！', '还没有选择文件！', wx.ICON_QUESTION)                 #消息框的几种类型
            #print 0
        else:
            files = []
            ids = self.fileList.GetChecked()
            i = 0
            for f in self.fileList.GetItems():
                #print f
                #print i in ids
                if i in ids:
                    files.append(os.path.join(self.readDir , f))
                i = i + 1
            #print files
            #print files
            self.speek.toWavList(files)
        
    def onPause(self , t = None):
        threading.Thread(None,self.pause).start()
    #暂停
    def pause(self ):
        print u"暂停"
        self.speek.pause()

    def onResume(self , t = None):
        threading.Thread(None,self.resume).start()
    #继续
    def resume(self):
        print u"继续"
        self.speek.resume()
        
    
    #停止
    def stop(self , t):
        print u"停止"
        self.speek.stop()
        
    #显示信息
    def info(self , s = None):
        if s != None:
            self.GetStatusBar().SetLabel(s)
            
    #显示现在读的文本
    def showFile(self , text):
        self.textArea.WriteText(text)
        
    #显示现在读的文本
    def showPoi(self , startMark , endMark):
        #self.textArea.SetInsertionPoint(0)
       
            if endMark != 0:
                self.textArea.SetStyle(self.start, self.end, wx.TextAttr("BLACK", self.textArea.GetBackgroundColour()))
                
            self.textArea.SetStyle(startMark, endMark, wx.TextAttr("WHITE", "BLUE"))
            #self.textArea.sc
            self.start = startMark
            self.end = endMark
            self.textArea.SetInsertionPoint(startMark)
            all = 0
#        for i in range(0 ,self.textArea.GetNumberOfLines()):
#            all = all + self.textArea.GetLineLength(i)
#            #print u"到" , i , u"行,长=" , all  , startMark
#            if(all >= startMark):
#                print u"当前为" , i , u"行 "
#                if self.currentLine != i:
#                    self.textArea.ScrollLines(i)
#                    self.textArea.SetInsertionPoint(startMark)
#                    self.currentLine = i
#                    #print i
#                break
        #points = self.textArea.GetFont().GetPointSize()  # get the current size
        #f = wx.Font(points+3, wx.ROMAN, wx.ITALIC, wx.BOLD, True)
        #self.textArea.SetStyle(63, 77, wx.TextAttr("BLUE", wx.NullColour, f))
    
  
    def add_news(self,news):
        url , title , content = news
        #print title
        while True:
            #print self.fileList.GetCount()
            if self.fileList.GetCount() <= 20:
                self.fileList.Append(title)
                self.news_list.append(news)
                break
            else:
                time.sleep(1)
                #print "sleep 1"
            
if __name__ == '__main__':
    
    app = wx.PySimpleApp(0)
    frame = text()
    app.SetTopWindow(frame)
    frame.Show()
    app.MainLoop()
    
  

